import type { Plugin } from 'vite';
import fs from 'fast-glob';

interface PreloadImagesOptions {
  dir: string;
  attrs: {
    rel: 'prefetch' | 'preload';
  };
}
export const preloadImages = (options: PreloadImagesOptions): Plugin => {
  const { dir, attrs = {} } = options;
  const assetsImages: string[] = [];
  return {
    name: '1vite-2plugin-image-prefetch',

    generateBundle(_, bundle) {
      const values = Object.values(bundle);
      const files = fs.sync(dir);
      values.forEach((item) => {
        if (files.includes(Reflect.get(item, 'originalFileName'))) {
          assetsImages.push(Reflect.get(item, 'fileName'));
        }
      });
    },

    transformIndexHtml(_, ctx) {
      let images: string[] = [];
      if (ctx.server) {
        const files = fs.sync(dir);
        const base = ctx.server?.config.base;
        images = files.map((file) => base + file);
      } else {
        images = assetsImages;
      }
      return images.map((href) => {
        return {
          tag: 'link',
          attrs: {
            rel: 'prefetch',
            as: 'image',
            href: href,
            ...attrs,
          },
        };
      });
    },
  };
};
